-
Notifications
You must be signed in to change notification settings - Fork 23
Даниил Павлов, Беззнаковое большое целое число #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
|
|
||
| class BigBigInt { | ||
|
|
||
| private String value;//Хранимое значение исходного огромного числа (bbInt) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Есть более эффективные способы хранить число. char - это два байта, в каждом char помещается только одна цифра числа.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вообще, замечание такое же, как и к Сергею - абстрагируйтесь от конкретного типа хранилища данных. То есть ваша бизнес-логика (код, который решает поставленную задачу) не должна знать, как именно вы храните число. Сделайте набор методов по работе с хранилищем (получить i-ую часть числа и т.д.), и пусть логика работает только с этими методами.
|
|
||
| private String value;//Хранимое значение исходного огромного числа (bbInt) | ||
|
|
||
| String getValue() {//Получение значения bbInt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
toString тогда уж
| //Обработка впередиидущих '0' и ' ' | ||
| int i; | ||
| for (i = 0; i < string.length(); i++) { | ||
| if (string.charAt(i) != '0' && string.charAt(i) != ' ') { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Похожую обработку делает метод String.replaceFirst. Но ваш вариант имеет свои преимущества (меньшее потребление памяти), так что можно оставить его.
| if (string.charAt(i) != '0' && string.charAt(i) != ' ') { | ||
| break; | ||
| } | ||
| if (i == string.length() - 1 && string.charAt(i) == '0') { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не обязательно проверять это внутри цикла. Можно проверит и после его окончания (в таком случае условие становится даже немного проще).
| return value; | ||
| } | ||
|
|
||
| BigBigInt(String string) { //Конструктор класса |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Называйте имена переменных и аргументов так, чтобы название соответствовало содержимому и описывало его. string почти ничего не говорит о том, что содержит переменная.
| string.getChars(i, string.length(), help, 0); | ||
| value = new String(help); | ||
| //Обработка ввода строки не содержащей чисел | ||
| if (value.compareTo("") == 0) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
equals
| //Преобразование строик в число без впередиидущих '0' и ' ' | ||
| char[] help = new char[string.length() - i]; | ||
| string.getChars(i, string.length(), help, 0); | ||
| value = new String(help); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
String.substring
| } | ||
| } | ||
|
|
||
| int Comparison(BigBigInt bbInt) {//Сравнение двух bbInt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Методы называются со строчной буквы (см. camelCase)
| int Comparison(BigBigInt bbInt) {//Сравнение двух bbInt | ||
| int result = -2; | ||
| if (this.value.compareTo(bbInt.value) == 0) { | ||
| result = 0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем нужна переменная result? Почему бы сразу не возвращать нужное значение?
|
|
||
| static BigBigInt addition(BigBigInt bbInt1, BigBigInt bbInt2) {//Сумма двух bbInt | ||
| if (bbInt1.Comparison(bbInt2) < 0) { | ||
| BigBigInt bbInt; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Другой вариант - сделать return addition(bbInt2, bbInt1)
| return result; | ||
| } | ||
|
|
||
| static BigBigInt addition(BigBigInt bbInt1, BigBigInt bbInt2) {//Сумма двух bbInt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Почему метод static?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Кроме того, в именах методов обычно используются глаголы, т.е. например add.
| String answer = ""; | ||
| String str2 = ""; | ||
| for (int i = 0; i < bbInt1.value.length() - bbInt2.value.length(); i++) { | ||
| str2 = str2 + "0"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
StringBuilder
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Кроме того, в случае сложения/вычитания заранее можно рассчитать максимальное количество разрядов. То есть даже без StringBuilder можно обойтись, если использовать массивы.
| return new BigBigInt(answer); | ||
| } | ||
|
|
||
| static BigBigInt subtraction(BigBigInt bbInt1, BigBigInt bbInt2) {//Разность двух bbInt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Код очень похож на addition. Можно ли как-нибудь устранить дублирование?
|
|
||
| static BigBigInt subtraction(BigBigInt bbInt1, BigBigInt bbInt2) {//Разность двух bbInt | ||
| if (bbInt1.Comparison(bbInt2) < 0) { | ||
| BigBigInt bbInt; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно объявить переменную и в той же строчке задать ей значение
| String ans = ""; | ||
| for (int j = bbInt1.value.length() - 1; j >= 0; j--) { | ||
| help += Integer.parseInt(bbInt2.value.charAt(i) + "") * Integer.parseInt(bbInt1.value.charAt(j) + ""); | ||
| ans = (help % 10) + ans; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
StringBuilder
| return new BigBigInt(counter); | ||
| } | ||
|
|
||
| static BigBigInt residue(BigBigInt bbInt1, BigBigInt bbInt2) {//Остаток от деления двух bbInt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Арифметический остаток переводится как remainder.
| do { | ||
| str2 = addition(bbInt, bbInt2).value; | ||
| bbInt = new BigBigInt(str2); | ||
| counter = addition(new BigBigInt(counter), new BigBigInt("1")).value; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Очень неэффективный способ деления. По сути - перебор. Нужно придумать что-нибудь эффективнее.
|
Помечаю задачу как завершенную. Если захотите, чтобы я прокомментировал код и дал какие-нибудь советы (без пересчета оценки, просто для собственного понимания задачи и приобретения опыта) - пишите. |
Долго пытался подвести все под двоичную систему, но в итоге ни к чему хорошему это так и не привело.Также до сих пор не смог сделать деление столбиком, просто сижу залипаю в экран, что-то пишу и через пару часов эти несчастные 10-20 строчек стираю.